<?php
/**
 * User: xuhong
 * Date: 2018/10/30
 */

namespace extend\wechat\mp;


use app\common\model\redis\Mp;

class Voucher
{

    /**
     * 公众号 凭证
     * @return array
     */
    public static function accessToken()
    {
        $mpConfig = self::getMp();

        $expireTime = 7000;
        $accessToken = (new Mp())->accessToken(['appid' => $mpConfig['mp_appid']], 'get');
//        $accessToken = '35_HVsqzU9ckTjRdVOOBiVir9kllApGEyl3IdxETZwssjrzo7bT74kO8if0NbhoqP8izayQSbKGnLw4k8gTd3W814o4vzI1g10lbdDTffN0M89Cur-5pwQ1cDL9Pv4O_c_Lf-O7XWtYLUnYhbXPHGHcAAAZYZOrder';
        if (empty($accessToken)) {
            $accessToken = Cert::accessToken($mpConfig['mp_appid'], $mpConfig['mp_appsecret']);
            $accessToken = json_decode($accessToken, true);
            if (empty($accessToken['access_token'])) {
                \app\common\service\Response::httpException(['status' => '0', 'msg' => 'access token获取失败']);
            }
            $res = (new Mp())->accessToken(['appid' => $mpConfig['mp_appid'], 'expires' => $expireTime, 'access_token' => $accessToken['access_token']], 'set');
            if (empty($res)) {
                \app\common\service\Response::httpException(['status' => '0', 'msg' => 'redis保存失败']);
            } else {
                $accessToken = $accessToken['access_token'];
            }
        }
        $mpConfig['access_token'] = $accessToken;
        return $mpConfig;
    }

    /**
     * 公众号 jssdk 凭证
     * @return array
     */
    public static function jsTicket()
    {
        $mpConfig = self::accessToken();

        $expire_time = time() + 7000;
        // 判断是否有jsapi_ticket 或者 jsapi_ticket 是否已经过期
        // 如果过期就进行更新
        if (empty($mpConfig['jsapi_ticket'])
            || time() >= $mpConfig['jsapi_ticket_expire']
        ) {
            // 获取 jsapi_ticket
            $res = Cert::jsTicket($mpConfig['access_token']);
            $res = json_decode($res, true);
        }

        // 没有过期的情况
        if (!empty($res["ticket"])) {
            $data_mp["jsapi_ticket"] = $res["ticket"];
            $data_mp["jsapi_ticket_expire"] = $expire_time;
            Configs::updateConfigs($data_mp, ['group' => 'mp']);
            $mpConfig = self::getMp();
        }
        return $mpConfig;
    }

    /**
     * 公众号 jssdk 签名
     * @param $uri
     * @return mixed
     */
    public static function mpSignature($uri)
    {
        $mpConfig = self::jsTicket();

        // 设置得到签名的参数
        $timestamp = time();
        $nonceStr = substr(md5(microtime()), 0, 16);

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket={$mpConfig["jsapi_ticket"]}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$uri}";

        $signPackage["appId"] = $mpConfig["appid"];
        $signPackage["nonceStr"] = $nonceStr;
        $signPackage["timestamp"] = $timestamp;
        $signPackage["url"] = $uri;
        $signPackage["rawString"] = $string;
        $signPackage["signature"] = sha1($string);;

        \View::share('wechat_sign_package', $signPackage);

        return $signPackage;
    }

    protected static function getMp()
    {
        return config('mp.');
    }
}